package services;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import domain.Event;
import domain.Participant;

import repositories.ParticipantRepository;
import security.LoginService;
import security.UserAccount;

@Service
@Transactional
public class ParticipantService {
	// Managed repository -----------------------------------------------------
	@Autowired
	private Md5PasswordEncoder encoder;
	
	@Autowired
	private ParticipantRepository participantRepository;
	
	// Constructors -----------------------------------------------------------
	
	public ParticipantService(){
		super();
	}
	
	// Simple CRUD methods ----------------------------------------------------
	
	public Participant create() {
		return new Participant();
	}

	public void save(Participant p) {
		Assert.notNull(p);
		if(p.getId()==0)
		p.getUserAccount().setPassword(encoder.encodePassword(p.getUserAccount().getPassword(),null));
		participantRepository.save(p);
	}
	
	// Other business methods -------------------------------------------------
	
	public Participant findByPrincipal() {
		UserAccount u = LoginService.getPrincipal();
		Participant p = participantRepository.findByUserAccountId(u.getId());
		return p;
	}
	
	public Collection<Participant> findParticipantsByEvent(Event event){
		Collection<Participant> participants = participantRepository.findParticipantsByEvent(event.getId());
		return participants;
		
	}
}
